﻿using SqlSugar;
using System.Reflection;

namespace LowCoding.Application
{
    /// <summary>
    /// Object扩展方法
    /// </summary>
    public static class ObjectExtension
    {
        /// <summary>
        /// 获取实体特性中的表名
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string GetTableName(this Type type)
        {
            var attr = type.GetCustomAttribute(typeof(SugarTable));
            if (attr == null) return string.Empty;

            var sugarAttr = (SugarTable)attr;
            return sugarAttr?.TableName;
        }

        /// <summary>
        /// 获取数据库字段名
        /// </summary>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetColumnName(this Type type, string name)
        {
            var property = type.GetProperty(name);
            var sugarAttribute = (SugarColumn)property.GetCustomAttributes(true)
                .First(it => it is SugarColumn);
            return sugarAttribute?.ColumnName;
        }
    }
}